<template>
  <div>

    <el-button
      @click="drawer = true"
      style="margin-top: 30px; margin-left: 30px"
    >
      请假进度查询&草稿箱
    </el-button>
    <!-- 请假进度弹窗 -->
    <el-drawer
      title="请假进度"
      :visible.sync="drawer"
      size="60%"
      :append-to-body="true"
      :with-header="false"
    >
      <div>
        <el-tabs style="margin-left: 30px" v-model="activeName">
          <el-tab-pane label="审核中" name="first">
            <el-table :data="pendingTableData" style="width: 100%">
              <el-table-column
                prop="startTime"
                label="开始时间"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="endTime"
                label="结束时间"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="leaveName"
                label="请假类别"
              ></el-table-column>
              <el-table-column
                prop="teacherName"
                label="审批教师"
              ></el-table-column>
              <el-table-column label="请假原因">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="showLeaveReason(scope.row.leaveReason)"
                    >打开</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
           
                  <el-button
                    size="mini"
                    type="text"
                    @click="confirmLeave(scope.row)"
                    >撤销</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="已审核" name="second">
            <el-table :data="approvedTableData" style="width: 100%">
              <el-table-column
                prop="startTime"
                label="开始时间"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="endTime"
                label="结束时间"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="leaveName"
                label="请假类别"
              ></el-table-column>
              <el-table-column
                prop="teacherName"
                label="审批教师"
              ></el-table-column>
              <el-table-column label="请假原因">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="showLeaveReason(scope.row.leaveReason)"
                    >打开</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="leaveStatusName"
                label="状态"
              ></el-table-column>
      
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="confirmDeleteLeave(scope.row)"
                    >删除</el-button>
                  <el-button @click="getReason(scope.row)" type="text" size="mini" >
                   查看驳回原因
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="草稿箱" name="third">
            <el-table :data="drafts" style="width: 100%">
              <el-table-column
                prop="startTime"
                label="日期范围"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="endTime"
                label="时间范围"
                width="180"
                :formatter="formatDate"
              ></el-table-column>
              <el-table-column
                prop="leaveName"
                label="请假类别"
              ></el-table-column>
              <el-table-column
                prop="teacherName"
                label="审批教师"
              ></el-table-column>
              <el-table-column label="请假原因">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="showLeaveReason(scope.row.leaveReason)"
                    >打开</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template v-slot="scope">
                  <el-button size="mini" type="text" @click="updateStutas(scope.row)"
                    >提交</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    @click="openEditDrawer(scope.row)"
                    >修改</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    @click="confirmDeleteLeave(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

        <el-drawer
          title="请假原因"
          :append-to-body="true"
          :before-close="handleClose"
          :visible.sync="innerDrawer"
          :with-header="false" 
        >
          <h1 style="font-size: 24px; font-weight: bold; padding: 16px">
            请假原因
          </h1>
          <div style="background-color: #f5f7fa">
            <p style="font-size: 21px; padding: 16px">{{ leaveReason }}</p>
          </div>
        </el-drawer>

        <el-drawer
        
          title="修改请假申请"
          :visible.sync="editDrawer"
          :before-close="handleEditClose"
          :with-header="false"
          :append-to-body="true"
        >
          <h1 style="font-size: 24px; font-weight: bold; padding: 16px">
            修改请假信息
          </h1>
          <el-form
            :data="pendingTableData"
            :model="quarmdata"
            :rules="rules"
            size="medium"
            label-width="100px"
          >
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="quarmdata.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 300px"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="quarmdata.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 300px"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="请假类别" prop="leaveType">
              <el-select
                v-model="quarmdata.leaveType"
                placeholder="请选择请假类别"
                clearable
              >
                <el-option
                  v-for="item in field106Options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审批教师" prop="teacherId">
              <el-select
                v-model="quarmdata.teacherId"
                placeholder="请选择审批教师"
                clearable
              >
                <el-option
                  v-for="item in field107Options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请假原因" prop="leaveReason">
              <el-input
                v-model="quarmdata.leaveReason"
                type="textarea"
                placeholder="请输入请假原因"
                :autosize="{ minRows: 4, maxRows: 4 }"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateLeaves"
                >确认修改</el-button
              >
              <el-button @click="editDrawer = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-drawer>
      </div>
    </el-drawer>

    <el-row style="margin-top: 20px; top: 2px; left: 250px" :gutter="15">
      <h1 style="font-size: 24px; font-weight: bold">员工请假</h1>
      <el-form
        ref="elForm"
        :model="quarmdata"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="quarmdata.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 400px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="quarmdata.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 400px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假类别" prop="leaveType">
          <el-select
            v-model="quarmdata.leaveType"
            placeholder="请选择请假类别"
            clearable
            :style="{ width: '50%' }"
          >
            <el-option
              v-for="item in field106Options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审批教师" prop="teacherName">
          <el-select
            v-model="quarmdata.teacherId
            "
            placeholder="请选择审批教师"
            clearable
            :style="{ width: '50%' }"
          >
            <el-option
              v-for="item in field107Options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假原因" prop="leaveReason">
          <el-input
            v-model="quarmdata.leaveReason"
            type="textarea"
            placeholder="请输入请假原因"
            :autosize="{ minRows: 4, maxRows: 4 }"
            :style="{ width: '50%' }"
          ></el-input>
        </el-form-item>
        <el-col :span="18">
          <el-form-item>
            <el-button type="primary" @click="submitForm">确认提交</el-button>
            <el-button @click="Draft">存为草稿</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import {
  createleave,
  getstatusOne,
  getteacherPage,
  getstatusZero,
  updateleave,
  statusDraft,
  deleteleave,
  getstatusDraft,
  saveDraft,
  cancel,
  getReason
} from "@/api/qingjia/index";

export default {
  data() {
    return {

      demoId:'',
      leaveStatus:0,
      drawer: false,
      innerDrawer: false,
      editDrawer: false,
      activeName: "first", // 默认选中审核中的标签
      quarmdata: {
     
        startTime: null,
        endTime: null,
        leaveReason: "",
        leaveType: "",
        teacherId: "",
        teacherName:''
      },
      leaveReason: "",
      pendingTableData: {
        leaveType: "",
        leaveReason: "",
        teacherId: "",
        startTime:"",
        endTime:""
      },
      
turnDownReason:'',
      approvedTableData: {
        leaveType: "",
        leaveReason: "",
        teacherId: "",
        startTime:"",
        endTime:"",
        leaveStatus: "",
        leaveStatusName:""
      },
        
      
      drafts: {
        id: "",
        leaveType: "",
        leaveReason: "",
        teacherId: "",
        startTime:"",
        endTime:"",
        leaveStatus: "",
        leaveStatusName:""
      },
      rules: {
        startTime: [
          {
            required: true,
            message: "时间范围不能为空",
            trigger: "change",
          },
          {
          validator: this.validateTimeRange,
          trigger: ["change", "blur"],
        },
        ],
        endTime: [
          {
            required: true,
            message: "时间范围不能为空",
            trigger: "change",
          },
          {
          validator: this.validateTimeRange,
          trigger: ["change", "blur"],
        },
        ],
        leaveType: [
          {
            required: true,
            message: "请选择请假类别",
            trigger: "change",
          },
        ],
        teacherId: [
          {
            required: true,
            message: "请选择指导教师",
            trigger: "change",
          },
        ],
        leaveReason: [
          {
            required: true,
            message: "请输入请假原因",
            trigger: "blur",
          },
        ],
      },
      field106Options: [
        { label: "事假", value: 1 },
        { label: "病假", value: 2 },
        { label: "公假", value: 0 },
      ],
      field107Options: [], // 教师列表
    };
  },
  mounted() {
    this.getteachers(); // 组件加载时获取教师数据'
    this.getLeaveStatuses(); // 获取请假状态
    
  },

  methods: {
    validateTimeRange(rule, value, callback) {
      console.log('Validating time range:', this.quarmdata.startTime, this.quarmdata.endTime);
    const startTime = this.quarmdata.startTime;
    const endTime = this.quarmdata.endTime;



    if (new Date(startTime) >= new Date(endTime)) {
      callback(new Error("开始时间必须早于结束时间"));
    } else {
      callback();
    }
  },
    getReason(row){
      getReason({id:row.id}).then(res => {
        for (let i = 0; i < res.data.length; i++) {
          this.turnDownReason=res.data[i].turnDownReason
          this.$notify({
          title: '驳回原因',
          message: res.data[i].turnDownReason,
          duration: 0
        });
        }
      })
    },
    
    confirmLeave(row){
      this.$confirm('确定要提交吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cancel({id: row.id}).then(() => {
      this.$message.success("提交成功");
      this.editDrawer = false; // 关闭编辑抽屉
      this.getLeaveStatuses(); // 重新加载请假列表+
    })
  }).catch(() => {
    this.$message.info("已取消提交");
  });
    },
    updateStutas(row) {
  this.$confirm('确定要提交吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    statusDraft({id: row.id}).then(() => {
      this.$message.success("提交成功");
      this.editDrawer = false; // 关闭编辑抽屉
      this.getLeaveStatuses(); // 重新加载请假列表+
    })
  }).catch(() => {
    this.$message.info("已取消提交");
  });
},
    formatDate(row, column, cellValue, index) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    async getteachers() {
      try {
        this.loading = true;
        const res = await getteacherPage();
        this.field107Options = res.data.list; // 假设返回的数据格式正确
      
      } finally {
        this.loading = false;
      }
    },
    Draft() {
      saveDraft(this.quarmdata).then(() => {
        this.$message.success("存草稿成功");
        this.editDrawer = false; // 关闭编辑抽屉
        this.getLeaveStatuses(); // 重新加载请假列表
      });
    },
    getLeaveStatuses() {
      getstatusZero().then((res) => {
    
        this.pendingTableData = res.data.map(item => ({
          ...item,
          leaveName: item.leaveType === 1 ? "事假" : item.leaveType === 2 ? "病假" : "公假",
        }));

      });
      getstatusOne().then((res) => {

        this.approvedTableData = res.data.map(item => ({
          ...item,
          leaveName: item.leaveType === 1 ? "事假" : item.leaveType === 2 ? "病假" : "公假",
      
        }));
        for(let i = 0; i < res.data.length; i++){
              switch(res.data[i].leaveStatus){
                case 1:
                  this.approvedTableData[i].leaveStatusName = "已通过";
                  break;
                case 2:
                 this.approvedTableData[i].leaveStatusName = "已驳回";
                  break;
       
              }
            }  
      });
      getstatusDraft().then(res => {
        this.drafts = res.data.map(item => ({
          ...item,
          leaveName: item.leaveType === 1 ? "事假" : item.leaveType === 2 ? "病假" : "公假",
        }));
       
        
      })
    },

    showLeaveReason(reason) {
      this.leaveReason = reason; // 将请假原因赋值给 leaveReason
      this.innerDrawer = true; // 打开内嵌抽屉
    },

    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          const requestDataOne = {
      quarmdata: this.quarmdata,
      draftStatus: this.draftStatusOne

    };
          createleave(this.quarmdata)
            .then((response) => {
              this.$message({
                message: "请假申请提交成功",
                type: "success",
              });
              this.resetForm(); // 提交后重置表单
            })
            .catch((error) => {
              this.$message.error("提交失败");
            });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    resetForm() {
      this.$refs["elForm"].resetFields(); // 重置表单
      this.quarmdata = {
        startTime: null,
        endTime: null,
        leaveReason: "",
        leaveType: "",
        teacherId: "",
      };
    },

    openEditDrawer(leave) {
      this.quarmdata = {
        id:leave.id,
        startTime: leave.startTime,
        endTime: leave.endTime,
        leaveReason: leave.leaveReason,
        leaveType: leave.leaveType,
        teacherId: leave.teacherId,
      };
      this.editDrawer = true; // 打开编辑抽屉
    },

 updateLeaves() {
  const data=this.quarmdata;
  updateleave(data).then(() => {
    this.$message.success("请假信息更新成功");
    this.editDrawer = false; // 关闭编辑抽屉
    this.getLeaveList(); // 重新加载请假列表
  });
},
     

    confirmDeleteLeave(leave) {
    
  this.$confirm("确定要删除该请假申请吗？")
    .then(() => {
      this.loading = true; // 显示加载状态
      deleteleave(leave.id)
        .then(() => {
          this.$message.success("请假申请删除成功");
          this.getLeaveList(); // 重新加载请假列表
        
        })
        .finally(() => {
          this.loading = false; // 隐藏加载状态
        });
    })
    },

    handleClose() {
      this.innerDrawer = false; // 关闭请假原因抽屉
    },
    handleEditClose() {
      this.editDrawer = false; // 关闭编辑抽屉
    },
  },
};
</script>